﻿using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Core.Extension;
using Core.Mgrs;
using Logic.Global;

namespace Core.Base.Module
{
    /// <summary>
    /// 所有模块的管理类
    /// </summary>
    public class ModuleMgr : Singleton<ModuleMgr>
    {
        public BaseModule CurModule { get; private set; } = null;

        private MainModule _mainModule;

        /// <summary>
        /// 加载某模块
        /// </summary>
        /// <param name="tuple">加载模块时传入的数据</param>
        /// <param name="onFinish">模块加载完成的回调</param>
        /// <param name="onFail">加载失败的回调</param>
        /// <typeparam name="T">模块类</typeparam>
        public void LoadModule<T>(ITuple tuple = null, Action onFinish = null, Action onFail = null)
            where T : BaseModule
        {
            var type = typeof(T);
            var nextModule = Activator.CreateInstance(type, true) as T;
            var moduleAttribute = type.GetCustomAttribute(typeof(ModuleAttribute), false) as ModuleAttribute;
            nextModule?.OnLoadStart(moduleAttribute, tuple, delegate
            {
                CurModule?.OnUnload();
                CurModule = nextModule;
                if (CurModule.IsMainModule && _mainModule == null)
                    _mainModule = CurModule as MainModule;
                onFinish?.Invoke();
            }, delegate { onFail?.Invoke(); });
        }

        /// <summary>
        /// 重新加载当前模块
        /// </summary>
        /// <param name="tuple">重载时传入的数据</param>
        public void ReloadCurModule(ITuple tuple = null)
        {
            CurModule.OnUnload();
            Type type = CurModule.GetType();
            CurModule = Activator.CreateInstance(type, true) as BaseModule;
            var moduleAttribute = type.GetCustomAttribute(typeof(ModuleAttribute), false) as ModuleAttribute;
            CurModule?.OnLoadStart(moduleAttribute, tuple);
        }
    }
}